package com.smartkey.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.os.IBinder;
import android.os.IHardwareService;
import android.os.RemoteException;

public class FlashLightUtil {

	private Camera mCamera;
	private Camera.Parameters mParam;
	private Context context;

	private static FlashLightUtil INSTANCE = new FlashLightUtil();

	private FlashLightUtil() {
	}

	public static final FlashLightUtil getInstance(Context context) {
		if (INSTANCE.context == null) {
			INSTANCE.context = context;
		}
		return INSTANCE;
	}

	/**
	 * 打开闪光灯 XIAOMI
	 */
	public void turnOnFlashLightXIAOMI() {
		Intent localIntent = new Intent("miui.intent.action.TOGGLE_TORCH");
		localIntent.putExtra("miui.intent.extra.IS_TOGGLE", true);
		context.sendBroadcast(localIntent);
	}

	/**
	 * 关闭闪光灯 XIAOMI
	 */
	public void turnOffFlashLightXIAOMI() {
		Intent localIntent = new Intent("miui.intent.action.TOGGLE_TORCH");
		localIntent.putExtra("miui.intent.extra.IS_TOGGLE", false);
		context.sendBroadcast(localIntent);
	}

	/**
	 * 打开闪光灯
	 */
	public void turnOnFlashLight() {
		try {
			mCamera = Camera.open();
			mParam = mCamera.getParameters();
			mParam.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
			mCamera.setParameters(mParam);
			mCamera.autoFocus(new AutoFocusCallback() {

				@Override
				public void onAutoFocus(boolean success, Camera camera) {

				}
			});
			mCamera.startPreview();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭闪光灯
	 */
	public void turnOffFlashLight() {
		if (mCamera == null || mParam == null) {
			return;
		}
		try {
			mParam.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
			mCamera.setParameters(mParam);
			mCamera.release();
			mParam = null;
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void switchFlashLight(boolean isEnable) {
		try {
			Method method = Class.forName("androd.os.ServiceManager")
					.getMethod("getService", String.class);
			IBinder binder = (IBinder) method.invoke(null,
					new Object[] { "hardware" });
			IHardwareService hardwareService = IHardwareService.Stub
					.asInterface(binder);
			hardwareService.setFlashlightEnabled(isEnable);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
}
